package springcloud.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Author 咕唧
 * @Date 2022/6/28 11:34
 * @Version 1.0
 * 后置过滤器
 */
@Component
public class MyPostFilter extends ZuulFilter {
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 后置过滤器
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
     * 过滤器的优先级
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+100;
    }

    /**
     * 是否开启当前过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        return currentContext.sendZuulResponse();
    }

    /**
     * 过滤器需要执行的操作
     * @return
     * @throws ZuulException
     */
    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        System.out.println("MyPostFilter的run方法执行了");
        //获取参数
        RequestContext currentContext = RequestContext.getCurrentContext();
        Object username = currentContext.get("username");

        //通过io流的方式，获取请求的返回的数据
        InputStream responseDataStream = currentContext.getResponseDataStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseDataStream));
        String line = null;

//        String s = bufferedReader.readLine();
        try {
            while ((line=bufferedReader.readLine())!=null) {
                System.err.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
